<!--

之前把安监和质量分开了，加了新功能：安监可以添加队安全工程师以外的人，并且，分包商的安全工程师如果出场了，还是要显示出来，并且显示成已出场
2021-11-15又喊恢复转去，只查安全工程师，和班组长，也不管什么已出场不出场了
-->


<template>
  <!-- 区域表单弹窗 -->
  <a-modal
    :title="headerTitle"
    :visible.sync="dialogVisible"
    @cancel="handleCancel"
    width="900px"
  >
    <!-- 表单 -->
    <a-spin :spinning="loading">
      <a-form-model
        ref="ruleForm"
        :model="forms"
        :rules="rules"
        :labelCol="{ span: 8 }"
        :wrapperCol="{ span: 14 }"
        style="max-height: 500px; overflow: auto"
      >
        <div id="dialogDistrictBox">
          <a-row>
            <a-col :lg="12" :md="12" :sm="12">
              <a-form-model-item prop="dutySubcontractor" label="分包商">
                <div v-if="editModel == 2" style="margin-top: -3px">{{ forms.dutySubcontractorName }}</div>
                <select-subcontractor
                  v-if="dialogVisible && editModel != 2"
                  :form="form"
                  showSearch
                  :disabled="editModel == 2"
                  :option.sync="dutySubcontractor"
                  v-model="forms.dutySubcontractor"
                ></select-subcontractor>
              </a-form-model-item>
            </a-col>
            <a-col :lg="12" :md="12" :sm="12">
              <a-form-model-item prop="dutyPeople" label="责任人">
                <div v-if="editModel == 2" style="margin-top: -3px">
                  <ellipsis tooltip :length="20">{{ forms.dutyPeopleName }}</ellipsis>
                </div>
                <SelectPersonByProject
                  v-if="dialogVisible && editModel != 2"
                  :id="form.branchCompanyId"
                  :disabled="editModel == 2"
                  v-model="forms.dutyPeople"
                  mode="multiple"
                  :maxTagCount="2"
                  statusCode="0"
                  :projectId="form.projectId"
                  :showSearch="true"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :lg="24" :md="24" :sm="24">
              <a-form-model-item prop="rectificationPeople" label="整改人" v-if="moduleType == 0">
                <div v-if="editModel == 2" style="margin-top: -3px">
                  <a-tag style="font-size:16px;" v-for="(item, index) in forms.rectificationPeopleName" :key="index">
                    {{ item }}
                  </a-tag>
                  <span v-if="!forms.rectificationPeople || forms.rectificationPeople.length == 0">无</span>
                </div>
                <a-spin :spinning="spinning || spinningTwo" v-else style="max-height: 200px; overflow-y: auto">
                  <a-checkbox-group v-model="forms.rectificationPeople" style="margin-top: 6px">
                    <a-checkbox v-for="i in rectificationPeoples" :key="i.id" :value="i.id">
                      <ellipsis tooltip :length="20">
                        {{ i.name }}
                      </ellipsis>
                    </a-checkbox>
                  </a-checkbox-group>
                  <span v-if="!rectificationPeoples || rectificationPeoples.length == 0">无</span>
                </a-spin>
              </a-form-model-item>
              <a-form-model-item prop="rectificationPeoples" label="整改人" v-if="moduleType == 1">
                <div v-if="editModel == 2" style="margin-top: -3px">
                  <a-tag style="font-size:16px;" v-for="(item, index) in displayNames" :key="index">
                    {{ item }}
                  </a-tag>
                  <span v-if="!forms.rectificationPeople || forms.rectificationPeople.length == 0">无</span>
                </div>
                <div class="flex" v-else>
                  <a-spin :spinning="spinning || spinningTwo" style="max-height: 200px; overflow-y: auto">
                    <a-checkbox-group v-model="forms.rectificationPeoples" style="margin-top: 6px">
                      <a-checkbox v-for="i in rectificationPeoples" :key="i.id" :value="i.id">
                        <ellipsis tooltip :length="20">
                          {{ i.name }}
                        </ellipsis>
                      </a-checkbox>
                    </a-checkbox-group>
                    <span v-if="!rectificationPeoples || rectificationPeoples.length == 0">无</span>
                  </a-spin>
                  <a-button style="margin-left: 20px;" @click="openGroup">添加</a-button>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="status"
                label="状态"
              >
                <a-select
                  :disabled="editModel == 2"
                  v-model="forms.status"
                >
                  <a-select-option :value="'1'">启用</a-select-option>
                  <a-select-option :value="'0'">停用</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              v-if="moduleType !=  1"
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="partIds"
                label="施工内容"
              >
                <SelectTreeSubItem
                  :labels.sync="forms.partNames"
                  :labelInValue="true"
                  :projectId="form.projectId"
                  :treeCheckable="true"
                  v-model="forms.partIds"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :lg="24"
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                prop="dutyAreaDescription"
                label="责任区域描述"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 19 }"
              >
                <BaseInput
                  :maxLength="300"
                  :disabled="editModel == 2"
                  v-model="forms.dutyAreaDescription"
                  type="textarea"
                  :rows="6"
                ></BaseInput>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div slot="footer" class="btn_box">
      <a-button
        :loading="loading"
        v-if="editModel != 2"
        type="primary"
        class="button_right"
        @click="handleOk"
      >提交
      </a-button>
      <a-button
        type="primary"
        @click="handleCancel"
      >关闭
      </a-button>
    </div>

    <SelectGroupPeople @ok="groupOk" :visible.sync="groupVisible"
                       :projectId="form.projectId"
                       :subContractorId="forms.dutySubcontractor"
    />
  </a-modal>
</template>

<script>
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { Ellipsis } from '@/components' // 表格
import { set } from '@/api/quality/currency' // api
import { men } from '@/api/quality/quality' // api
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
// import SelectDutyPeople from '@/components/Select/SelectDutyPeople' // 分包商
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem'
import SelectGroupPeople from '@/views/quality/currency/subcontractorsDistrictSetting/SelectGroupPeople'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubcontractor,
    // SelectDutyPeople,
    SelectTreeSubItem,
    SelectPersonByProject,
    Ellipsis,
    SelectGroupPeople
  },
  props: {
    // 操作类型
    editModel: {
      type: [String, Number],
      default() {
        return 0
      }
    },
    // 显隐控件
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 表单
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return ''
      }
    },
    // 模块类型：0 质量；1 安监
    moduleType: {
      type: [String, Number],
      default() {
        return 0
      }
    }
  },
  computed: {
    spinningTwo() {
      return this.rectificationPeoples?.length == 0 && this.editModel == 2
    },
    //疑似未使用，保险起见不删除，怕了怕了
    rectificationPeople() {
      let rectificationPeople = []
      this.forms.rectificationPeople &&
      (rectificationPeople =
        [...this.rectificationPeoples]?.filter((item) => this.forms.rectificationPeople.includes(item.id)) ?? [])
      return rectificationPeople
    },
    // 与父组件绑定visible
    dialogVisible: {
      get: function() {
        return this.visible
      },
      set: function(e) {
        this.$emit('update:visible', e)
      }
    },
    displayNames() {
      return Object.values(this.forms.safeRectifierValue)
    }
  },
  data() {
    return {
      forms: {
        dutySubcontractor: '',
        safeRectifierValue: {},
        rectificationPeople: [],//原来的代码新增的时候是保存的id，但是列表显示人名又是用的这个字段，就尼码离谱，不晓得这代码咋跑起来的，
        //2021-11-4,安监专用修改，用来保存人名，用于列表显示，rectificationPeopleName不传名字了
        //id存下rectificationPeoples这个里面
        rectificationPeoples: []
      }, // 表单
      loading: false,
      groupVisible: false,
      dutySubcontractor: {}, // 分包商选中项
      spinning: false, // 整改人加载
      rectificationPeoples: [], // 整改人列表
      rules: {
        dutySubcontractor: [{ required: true, message: '请选择分包商', trigger: 'change' }],
        dutyPeople: [{ required: true, message: '请选择责任人', trigger: 'change' }],
        rectificationPeople: [{ type: 'array', required: true, message: '请选择整改人', trigger: 'blur' }],
        rectificationPeoples: [{ type: 'array', required: true, message: '请选择整改人', trigger: 'blur' }],
        partIds: [{ type: 'array', required: true, message: '请选择施工内容', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        dutyAreaDescription: [{ required: true, message: '请填写责任区域描述', trigger: 'change' }]
      },
      init: false
    }
  },
  methods: {
    openGroup() {
      if (!this.forms.dutySubcontractor) {
        return this.$noticeWarning('请选择分包商')
      }
      this.groupVisible = true
    },
    groupOk(e) {
      let { people, groupId } = e
      if (!this.rectificationPeoples.find(v => v.id === people.key)) {
        this.rectificationPeoples.push({ id: people.key, name: people.label, type: 1, groupId })
        if (!this.forms.rectificationPeoples) {
          this.forms.rectificationPeoples = []
        }
        this.forms.rectificationPeoples.push(people.key)
      }
    },
    handleOk() {
      if (this.moduleType == 0) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.loading = true
            this.$emit('confirm', this.forms)
          } else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.forms.menuType = 1
            this.forms.safeRectifier = {}
            this.forms.rectificationPeople = []
            // this.forms.safeRectifierValue = {}
            if (this.forms.rectificationPeoples) {
              this.forms.rectificationPeoples.map(v => {
                let res = this.rectificationPeoples.find(w => w.id === v)
                if (res) {
                  this.forms.rectificationPeople.push(res.name)
                  if (res.type === 1) {
                    this.forms.safeRectifier[v] = res.groupId
                  } else {
                    this.forms.safeRectifier[v] = res.type
                  }
                }
              })
            }
            this.loading = true
            this.$emit('confirm', this.forms)
          } else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
        // this.$console(this.forms)
      }
    },
    handleCancel() {
      this.dialogVisible = false
    },
    // 切换分包商获取整改人
    async handleChange(reset = true) {
      if (this.moduleType == 0) {
        this.$nextTick(() => {
          let id = this.dutySubcontractor.subContractorOrgId
          this.spinning = true
          // reset && this.$set(this.forms, 'rectificationPeople', [])
          men
            .getList({ subContractorId: this.forms.dutySubcontractor, projectId: this.form.projectId })
            .then((res) => {
              this.spinning = false
              if (res.data?.length > 0) {
                this.rectificationPeoples = res.data
              } else {
                this.rectificationPeoples.length > 0 && (this.rectificationPeoples = res.data)
              }
            })
            .catch((res) => {
              this.spinning = false
            })
        })
      } else {
        if (!this.forms.id) {
          // //下面两行，把已选的分包商的人，从forms已选中的数组中去掉。
          // if (this.forms.rectificationPeople && this.forms.rectificationPeople.length) {
          //   let remove = this.rectificationPeoples.filter(v => v.type === 0)
          //   this.forms.rectificationPeople = this.forms.rectificationPeople.filter(w => !(remove.find(v => v.id === w)))
          // }
          //
          // //把当前人员数组，不是分包商人的，删除掉，留下班级的人
          // this.rectificationPeoples = this.rectificationPeoples.filter(v => v.type === 1)

          this.forms.rectificationPeoples = []
          this.forms.rectificationPeople = []
          this.spinning = true
          let res = await men.getList3({
            subContractorId: this.forms.dutySubcontractor,
            projectId: this.form.projectId
          })
          this.spinning = false
          if (res.code === this.SUCCESS_CODE) {
            res.data.map(v => v.type = 0)
            this.rectificationPeoples = res.data
          }
        } else {
          if (this.init) {
            this.forms.rectificationPeoples = []
            this.forms.rectificationPeople = []
          }

          this.spinning = true
          let res = await men.getList3({
            subContractorId: this.forms.dutySubcontractor,
            projectId: this.form.projectId
          })
          this.spinning = false
          if (res.code === this.SUCCESS_CODE) {
            res.data.map(v => v.type = 0)
            if (this.init) {
              this.rectificationPeoples = res.data
            } else {
              res.data.map(v => {
                if (!this.rectificationPeoples.find(w => w.id === v.id)) {
                  this.rectificationPeoples.push(v)
                }
              })
            }
            this.init = true
            // console.log('this.rectificationPeoples')
            // this.$console(this.rectificationPeoples)
          }

        }
      }
      // this.$console(this.forms)
    }
  },
  watch: {
    dutySubcontractor(e) {
      if (e && Object.keys(e)?.length > 0 && e.subContractorOrgId) {
        this.handleChange()
      } else {
        this.forms.rectificationPeople?.length > 0 && (this.forms.rectificationPeople = [])
        this.rectificationPeoples.length > 0 && (this.rectificationPeoples = [])
      }
    },
    visible(e) {
      //安监
      if (this.moduleType == 1) {
        if (e) {
          this.$nextTick(() => {
            // 若操作为查看和编辑
            if (this.editModel != 0) {
              this.loading = true
              set.getDetail({ id: this.form.id })
                .then((res) => {
                  this.loading = false
                  if (res.code == 200) {
                    this.forms = res.data

                    //安监回显，恶心死人呐
                    if (!this.forms.rectificationPeoples) {
                      this.forms.rectificationPeoples = []
                    }
                    if (!this.forms.safeRectifierValue) {
                      this.forms.safeRectifierValue = {}
                    }
                    Object.keys(this.forms.safeRectifierValue).map(v => {
                      if (!this.forms.rectificationPeoples) {
                      }
                      this.forms.rectificationPeoples.push(v)

                      let temp = { id: v, name: this.forms.safeRectifierValue[v] }
                      if (this.forms.safeRectifier[v] == 0) {
                        temp.type = 0
                      } else {
                        temp.type = 1
                        temp.groupId = this.forms.safeRectifier[v]
                      }
                      this.rectificationPeoples.push(temp)
                    })
                  }
                })
                .catch((res) => {
                  this.loading = false
                })
            } else {
              this.forms = this.$assign(this.forms, this.form)
            }
          })
        } else {
          this.forms = {
            dutySubcontractor: '',
            safeRectifierValue: {},
            rectificationPeople: [],//原来的代码新增的时候是保存的id，但是列表显示人名又是用的这个字段，就尼码离谱，不晓得这代码咋跑起来的，
            //2021-11-4,安监专用修改，用来保存人名，用于列表显示，rectificationPeopleName不传名字了
            //id存下rectificationPeoples这个里面
            rectificationPeoples: []
          }
          this.init = false
          this.rectificationPeoples = []
          this.dutySubcontractor = []
          // 初始化表单
          this.$refs.ruleForm.clearValidate()
        }
      } else {
        if (e) {
          this.$nextTick(() => {
            // 若操作为查看和编辑
            if (this.editModel != 0) {
              this.loading = true
              set
                .getDetail({
                  id: this.form.id
                })
                .then((res) => {
                  this.loading = false
                  if (res.code == 200) {
                    this.forms = res.data
                  }
                })
                .catch((res) => {
                  this.loading = false
                })
            } else {
              this.forms = cloneDeep(this.form)
            }
          })
        } else {
          this.forms = {}
          this.rectificationPeoples = []
          this.dutySubcontractor = []
          // 初始化表单
          this.$refs.ruleForm.clearValidate()
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-checkbox-wrapper {
  margin-left: 0;
  width: 160px;
  overflow: hidden;
  height: 24px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
